package com.kgc.untils;

import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.*;
import com.kgc.vo.R;

import javax.servlet.http.HttpSession;
import java.util.Random;

/**
 * 短信类服务
 */
public class SendSMSUtils {

    // 阿里云申请短信服务后填写
    private static final String accessKeyId = "LTAI5tSTj4fNE6Ghm5M64YFF";  // 账户ID
    private static final String accessKeySecret = "LMOpa8Zxt3XYX6RtzkIl0scYldAUwC"; // 账户秘钥
    private static final String signName = "candy"; // 签名
    private static final String verifyCodeTemplate = "SMS_166376606"; // 短信模版

    // 限制发送短信的时间
    private static final Integer TIMEOUT = 60000; // 60s
    private static final String KEY_PHONE = "sms:phone:"; // Session,key前缀

    /**
     * 验证服务
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return
     * @throws Exception
     */
    private static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     * 发送验证码
     *
     * @param phone
     */
    public static R sendSms(String phone, HttpSession session) {
        System.out.println("=> 发送短信成功执行到此处！");
        // 验证短信频率
        String key = KEY_PHONE + phone; // sms:phone:13312345678
        Object obj = session.getAttribute(key);
        if (obj != null) {
            Long keyTime = (Long) obj; // 发送时间
            Long nowTime = System.currentTimeMillis(); // 当前时间
            if(nowTime-keyTime < TIMEOUT){
                return R.error("短信发送频率过快!");
            }
        }
        try {
            com.aliyun.dysmsapi20170525.Client client = SendSMSUtils.createClient(accessKeyId, accessKeySecret);
            // 验证码随机数
            String code = generateCode(6);
            // 存储验证码到Session
            session.setAttribute("code", code);
            System.out.println("=> 生成的验证码：" + code);
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName(signName)
                    .setTemplateCode(verifyCodeTemplate)
                    .setTemplateParam("{\"code\":\"" + code + "\"}");

            // 真实发送短信代码 测试时注释 ↓
//            client.sendSms(sendSmsRequest);
            // 发送验证码时间存储
            session.setAttribute(key, System.currentTimeMillis());
            return R.success("验证发送成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("验证发送失败!");
        }
    }


    /**
     * 生成指定位数的随机数字
     *
     * @param len
     * @return
     */
    private static String generateCode(int len) {
        len = Math.min(len, 8);
        int min = Double.valueOf(Math.pow(10, len - 1)).intValue();
        int num = new Random().nextInt(Double.valueOf(Math.pow(10, len + 1)).intValue() - 1) + min;
        return String.valueOf(num).substring(0, len);
    }

}
